﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Web;
using MyAspx.EasyFramework.DAL3;
using MyAspx.EasyFramework.EntityFramework;
using MyAspx.Framework.Common;
using System.Web.SessionState;
namespace WebUI.Services.Core
{
    /// <summary>
    /// 无刷新上传源码的一般处理程序
    /// </summary>
    public class SendCodeInfoHandler : IHttpHandler, IRequiresSessionState
    {
        FileInfoDAL _fileInfoDal = new FileInfoDAL();
        TagDAL _tagDal = new TagDAL();
        DownUrlDAL _downUrlDal  = new DownUrlDAL();
        SaleDetailDAL _saleDetailDal = new SaleDetailDAL();
        UserCodeRelationDAL _userCodeRelationDal = new UserCodeRelationDAL();
        commyaspxdbEntities _myaspxentities = new commyaspxdbEntities();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //主要处理逻辑
            var result = new []
            {
                //源码名称 0
                context.Request.Form["name"],            //1
                //源码的价格 1
                context.Request.Form["paynub"],       
                //源码下载的服务端地址 2
                context.Request.Form["codeserverurl"],    
                //源码图片集合 3
                context.Request.Form["codepics"],        //1
                //源码的类别 4
                context.Request.Form["codetype"],        
                //源码开发工具 5
                context.Request.Form["developtool"],      //1
                //源码的编程语言 6
                context.Request.Form["language"],        //1
                //源码使用的数据库 7
                context.Request.Form["database"],        //1
                //源码的.NET 框架 8
                context.Request.Form["framework"],        //1
                //源码标签 9
                context.Request.Form["tags"],            
                //源码外连接地址 10
                context.Request.Form["linkurl"],          
                //源码作者 11
                context.Request.Form["author"],           //1
                //源码作者联系方式 12
                context.Request.Form["contract"],        //1
                //源码的作者留言 13
                context.Request.Form["usermsg"],        
                //源码详细描述 14
                context.Request.Form["preview"],
                context.Request.Form["codeclassId"],
                   // saletypecode: saletypev, salepaynub:salepaynub
                    context.Request.Form["saletypecode"],
                context.Request.Form["salepaynub"]
                //1

            };
            string errMes = "";
            string curfid = GuidString.CreateNewGuidStr();
            int codetypeindex = -1;
                switch (result[4].ToLower())
            {
                case "webform":
                    codetypeindex = 1;
                    break;
                case "winform":
                        codetypeindex = 2;
                    break;
                case "winphone":
                        codetypeindex = 3;
                    break;
            }
            int saletypeid = 0;
            int salenub = 0;
            switch (result[16])
            {
                case "free":
                   saletypeid = _myaspxentities.my_saletype.Where(f => f.saletype == "free").First().id;
                    break;
                 case "score":
                        saletypeid = _myaspxentities.my_saletype.Where(f => f.saletype == "score").First().id;
                    salenub = int.Parse(result[17]);
                    break;
                     case "rmb":
                        saletypeid = _myaspxentities.my_saletype.Where(f => f.saletype == "rmb").First().id;
                           salenub = int.Parse(result[17]);
                    break;
            }
            my_fileinfo curFileinfo = new my_fileinfo()
            {
                fileid = curfid,
                codetype = codetypeindex.ToString(),
                filename = result[0],
                filedatabase = result[7],
                filedevlan = result[6],
                filevstype = result[5],
                filepics = result[3],
                codedes = result[14],
                codelang = result[6],
                contract = result[12],
                createuser = result[11],
                codeplftype = result[5],
                devtool = result[5],
                frameworkversion = result[8]//,
                //codeserverurl = result[2].ToString()
                ,
                //saletypeid = 
                fileclassid = int.Parse(result[15]),
                saletypeid = saletypeid,
                usermsg = result[13]
            };
            //源码基础详细入库
            int exec = _fileInfoDal.AddNewCodeBaseInfo(curFileinfo,out errMes); 
            //结束

            //源码标签入库
            //if (result[9].IndexOf(' ') > 0)
            //{
            //    var tags = result[9].Split(' ');
            //    foreach (string tag in tags)
            //    {
            //    var curTag = tag;
            //    //遍历插入当前源码的TAG信息
            //    int tagexec = _tagDal.AddNewCodeTagInfo(new my_tag()
            //{
            //    fileinfoid = curfid,
            //    tagname = tag,
            //    tagcreatedate = DateTime.Now.ToString()

            //});
            //     }
            //}
            if (result[9].Trim().Length > 0)
            {
                var tags = new String[] { };
                if (result[9].IndexOf(',') > 0)
                {
                    tags = result[9].Split(',');
                }
                else
                {
                    tags = result[9].Split(' ');
                }
                foreach (string tag in tags)
                {
                    var curTag = tag;
                    //遍历插入当前源码的TAG信息
                    int tagexec = _tagDal.AddNewCodeTagInfo(new my_tag()
                    {
                        fileinfoid = curfid,
                        tagname = tag,
                        tagcreatedate = DateTime.Now.ToString()

                    });
                }
            }
            //源码类型入库codetype
            // 源码下载信息入库
            int downexec = _downUrlDal.AddNewCodeDownInfo(new my_downurl()
            {
                downfileid = curfid,
                downsyseul = "",
                downurl = result[2].ToString()
            });

            //源码销售类型和销售金额入库
            try{_saleDetailDal.AddNewSaleDetail(new my_saledetail()
            {
            
                fileid = curfid,
                salenum = decimal.Parse(salenub.ToString()) 
            });}
            catch (Exception) { }

            //源码上传用户入库
            //int  userid 
            try
            {
                String curUserName = "sys";
                if (context.Session["myaspxuser"] != null)
                {
                    curUserName = context.Session["myaspxuser"].ToString();
                }
                //else
                //{
                    
                //}

                int curuserid =
                    _myaspxentities.my_users.First(
                        u => u.useregname == curUserName).userid;
                _userCodeRelationDal.AddUcr(new my_usercodererelation()
            {
                fileid = curfid,
                userid = curuserid/* _myaspxentities.my_users.First(u => context.Session != null && u.useregname == context.Session["myaspxuser"].ToString()).userid*/
            
            });
            }
            catch (Exception)
            {
                
                
            }
          
            //_myaspxentities.my_usercodererelation.Add(new my_usercodererelation()
            //{
            //    fileid = curfid,
            //    userid = _myaspxentities.my_users.First(u=>u.useregname ==context.Session["myaspxuser"] .ToString()) .userid
            // });
            // _myaspxentities.SaveChanges();


            if (exec == 1)
            {
                context.Response.Write("addok");
            }
            else
            {
                context.Response.Write(errMes);
             }
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
            //set { this = value; }
        }
    }
}